﻿using Snowflake;
using Step4.Unit4.Entities;
using Step4.Unit4.Models;
using Step4.Unit4.utils;
using Step4.Unit4.utils.Snowflake;
using System.Data.SqlClient;
using AutoMapper;

namespace Step4.Unit4.Services
{
    public class ProductService : IProductService
    {
        private readonly IdWorker _idWorker;
        private readonly IMapper _mapper; 
        public ProductService(IMapper mapper)
        {
            _idWorker = SnowflakeUtil.CreateIdWorker();
            _mapper = mapper;
        }

        public List<ProductViewModel> Search()
        {
            string sql = @"select P.Id,P.ProductName,P.CategoryName,P.Price,P.CreatedTime,U.NickName CreatedNickName ,P.UpdatedTime,C.NickName UpdatedNickName
                        from 
	                        Product P left join UserInfo U on P.CreatedUserId = u.Id 
	                        left join UserInfo C on P.UpdatedUserId = c.Id
                        where P.Deleted=0";

            return DbHelper.GetList<ProductViewModel>(sql);
        }

        public void Add(ProductCreateBo bo)
        {
            // 先将Bo对象，转化为DataModel(实体)
            // 因为Bo对象不能出现在Repository(数据访问层)之内，所以，将Bo转化为Entity
            // 
            var product = _mapper.Map<ProductCreateBo, Product>(bo);
            product.Id = _idWorker.NextId();

            string sql = "insert into Product values (@id,@productName,@categoryName,@price,@remark,@createdUserId,@updatedUserId,@createdTime,@updatedTime,@deleted)";
            SqlParameter[] sqlParameters = {
                new SqlParameter("@id",product.Id),
                new SqlParameter("@productName",product.ProductName),
                new SqlParameter("@categoryName",product.CategoryName),
                new SqlParameter("@price",product.Price),
                new SqlParameter("@remark",product.Remark),
                new SqlParameter("@createdUserId",product.CreatedUserId),
                new SqlParameter("@updatedUserId",product.UpdatedUserId),
                new SqlParameter("@createdTime",product.CreatedTime),
                new SqlParameter("@updatedTime",product.UpdatedTime),
                new SqlParameter("@deleted",product.Deleted)
            };

            DbHelper.ExecuteNonQuery(sql, sqlParameters);
        }

    }
}
